<template>
  <div class="login">
    <el-card class="card">
      <h2 class="title">管理员登录</h2>
      <el-form :model="form" :rules="rules" ref="form" label-width="80px">
        <el-form-item label="账号" prop="username">
          <el-input v-model="form.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input type="password" v-model="form.password"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSubmit">登录</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import axios from 'axios';

export default {
  data() {
    return {
      form: {
        username: '',
        password: '',
      },
      rules: {
        username: [{ required: true, message: '请输入账号', trigger: 'blur' }],
        password: [{ required: true, message: '请输入密码', trigger: 'blur' }],
      },
    };
  },
  methods: {
    handleSubmit() {
      this.$refs.form.validate(async valid => {
        if (valid) {
          try {
            const res = await axios.post('/api/login', this.form);
            console.log('res', res);
            if (res?.data.code === 0) {
              // 登录成功跳转到系统首页
              this.$router.push('/');
            } else {
              this.$message.error(res.data.msg);
            }
          } catch (error) {
            this.$message.error(error.response.data.message);
          }
        }
      });
    },
  },
};
</script>

<style>
.login {
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
}

.card {
  width: 400px;
}

.title {
  text-align: center;
  margin-bottom: 20px;
}
</style>
